package com.iw.adoms.action;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.iw.adoms.entity.QrBatch;
import com.iw.adoms.entity.neum.Status;
import com.iw.adoms.service.QrBatchService;
import com.iw.adoms.service.QrBoxCodeService;
import com.iw.adoms.service.QrGoodsCodeService;
import com.iw.core.orm.PageData;
import com.iw.core.utils.WebUtils;

@Controller
@RequestMapping("/adoms/qrBatch")
public class QrBatchAction extends BaseAction {
	private static final Logger LOGGER = Logger.getLogger(QrBatchAction.class);
	@Resource
	private QrBatchService qrBatchService;
	@Resource
	private QrGoodsCodeService qrGoodsCodeService;
	@Resource
	private QrBoxCodeService qrBoxCodeService;

	@RequestMapping("/list")
	public ModelMap list(HttpServletRequest request) {
		PageData<QrBatch> pageData = new PageData<QrBatch>();
		// 给pageData设置参数
		WebUtils.setPageDataParameter(request, pageData);
		pageData = qrBatchService.find(pageData);

		return new ModelMap(pageData);
	}

	@RequestMapping(value = "/new")
	public String addForm(Model model) {
		return "/adoms/qrBatch/input";
	}

	@RequestMapping(value = "/edit/{id}")
	public String editForm(@PathVariable("id") Integer id, Model model) {
		QrBatch qrBatch = qrBatchService.find(id);
		model.addAttribute(qrBatch);
		return "/adoms/qrBatch/input";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(QrBatch qrBatch) {
		if (qrBatch.isNew()) {
			qrBatchService.save(qrBatch);
		} else {
			qrBatchService.update(qrBatch);
		}

		return "redirect:/adoms/qrBatch/list";// 重定向
	}

	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(QrBatch qrBatch) {
		try {
			qrBatchService.create(qrBatch);
		} catch (Exception e) {
			LOGGER.error(e);
		}
		return "redirect:/adoms/qrBatch/list";// 重定向
	}

	@RequestMapping(value = "/delete/{id}")
	public String delete(@PathVariable("id") Integer id) {
		QrBatch qrBatch = qrBatchService.find(id);
		try {
			if (qrBatch.getStatus().equals(Status.QR_NOT_CREATE.getValue())) {
				qrGoodsCodeService.batchExecute("delete from QrGoodsCode g where g.box.id in (select b.id from QrBoxCode b where b.qrBatch.id = ?)", id);
				qrBoxCodeService.batchExecute("delete from QrBoxCode where qrBatch.id = ?", id);
				qrBatchService.delete(id);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/adoms/qrBatch/list";// 重定向
	}

	@RequestMapping(value = "/download/{id}")
	public void download(@PathVariable("id") Integer id, HttpServletRequest request, HttpServletResponse response, String storeName) {
		try {

			QrBatch qrBatch = qrBatchService.find(id);
			String realName = qrBatch.getCode() + "-" + qrBatch.getId() + "-1." + qrBatch.getCreateScale() + "-" + qrBatch.getBoxNum() + "." + qrBatch.getGoodsNum() + ".txt";

			String contentType = "text/html;charset=UTF-8";
			response.setContentType(contentType);
			request.setCharacterEncoding("UTF-8");
			BufferedOutputStream bos = null;

			response.setHeader("Content-disposition", "attachment; filename=" + realName);

			bos = new BufferedOutputStream(response.getOutputStream());

			try {
				Session session = qrBatchService.getBaseDao().getNewSession();
				Transaction tx = session.beginTransaction();

				ScrollableResults srs = session
						.createQuery(
								"select b.wCode as wCode,b.qrCode as qrCode,g.wCode as gwCode,g.qrCode as gqrCode,g.iCode as iCode from QrBoxCode b,QrGoodsCode g where g.box.id=b.id and b.qrBatch.id =:batchId")
						.setInteger("batchId", id).scroll();
				while (srs.next()) {
					String s = srs.getString(0) + "," + srs.getString(1) + "," + srs.getString(2) + "," + srs.getString(3) + "," + srs.getString(4) + "\r";
					bos.write(s.getBytes());
				}

				tx.commit();
				session.flush();
				session.clear();
				session.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			bos.flush();
			bos.close();
			qrBatch.setStatus(Status.QR_EXPORT.getValue());
			qrBatchService.update(qrBatch);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
